package com.slipper.system.setting.service;

import java.util.List;

import com.slipper.constants.Constants;
import com.slipper.core.cache.CacheKey;
import com.slipper.core.cache.CacheUtil;
import com.slipper.util.Tool;
import com.slipper.util.UUID;
import org.springframework.stereotype.Service;
import jakarta.annotation.Resource;

import com.slipper.system.setting.dao.SettingDao;
import com.slipper.system.setting.bo.SettingBO;

import com.slipper.core.transaction.ReadTransactional;
import com.slipper.core.transaction.WriteTransactional;

@Service
@ReadTransactional
public class SettingService {
    @Resource
    private SettingDao settingDao;

    @WriteTransactional
    public int save(SettingBO bo) {
        int result;
        if (Tool.isNotBlank(bo.getId())) {
            result = settingDao.update(bo);
        } else {
            bo.setId(UUID.getUUID());
            result = settingDao.insert(bo);
        }
        CacheUtil.remove(CacheKey.Setting.KEY);
        return result;
    }

    @WriteTransactional
    public int delete(SettingBO bo) {
        int result = settingDao.delete(bo);
        CacheUtil.remove(CacheKey.Setting.KEY);
        return result;
    }

    public SettingBO querySetting() {
        SettingBO result = CacheUtil.get(CacheKey.Setting.KEY, SettingBO.class);

        if (result == null) {
            List<SettingBO> settingList = settingDao.queryList(new SettingBO());
            for (int i=0; i<settingList.size(); i++) {
                if (i == 0) {
                    result = settingList.get(i);
                    CacheUtil.set(CacheKey.Setting.KEY, result, 60 * 60);
                } else {
                    this.delete(settingList.get(i));
                }
            }
        }

        if (result == null) {
            result = new SettingBO();
            result.setPasswordCheck(Constants.NO);
            this.save(result);
        }

        return result;
    }
}
